#pragma once
#include<iostream>
#include<pthread.h>
#include<stdio.h>
#include<functional>

class Thread
{
public:
    using func_t =std::function<void ()>;
    typedef enum status
    {
        NEW = 0,
        RUNNING,
        EXITED
    }status;

    //构造函数
    Thread(int num,func_t func)
    :_tid(0),
    _func(func),
    _status(NEW)
    {
        char name[64];
        snprintf(name,sizeof(name),"thread-%d",num);
        _name=name;
    }

    //执行函数
    static void*runHelper(void*args)
    {
        Thread *t=static_cast<Thread*>(args);
        
        t->_func();

        return nullptr;
    }

    //启动方法
    void run()
    {
        int n=pthread_create(&_tid,nullptr,runHelper,this);
        if(n!=0)
        {
            std::cout<<"线程创建失败"<<std::endl;
        }
        _status=RUNNING;
    }

    //线程等待
    void join()
    {
        int n=pthread_join(_tid,nullptr);
        if(n!=0)
        {
            std::cerr<<"线程等待失败"<<std::endl;
        }
        _status=EXITED;
    }

    //获取状态
    status Status(){return _status;}
    //获取线程名
    std::string name(){return _name;}
    //获取线程ID
    pthread_t threadId()
    {
        if(_status!=RUNNING)
        {
            std::cout<<"当前线程没有运行"<<std::endl;
            return 0;
        }

        return _tid;
    }

    //析构函数
    ~Thread()
    {}
    
private:
    int num;//编号
    std::string _name;//线程名
    func_t _func;//启动函数
    pthread_t _tid;//线程ID
    status _status;//线程状态
};